#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import logging
import traceback
from typing import Dict, Any

from fastapi import FastAPI, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles

from app.core.config import settings
from app.core.exceptions import BaseAppException
from app.core.logging import setup_logging, get_logger

# 设置日志
setup_logging()
logger = get_logger("main")

# 创建FastAPI应用
app = FastAPI(
    title=settings.APP_NAME,
    description=settings.APP_DESCRIPTION,
    version=settings.APP_VERSION,
    docs_url="/docs",
    redoc_url="/redoc",
    openapi_url="/openapi.json",
    debug=True  # 强制启用调试模式
)

# 配置静态文件服务
app.mount("/static", StaticFiles(directory="static"), name="static")

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该限制来源
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 添加一个简单的测试路由
@app.get("/api/v1/test")
async def test_endpoint():
    """测试API是否正常工作"""
    return {"status": "ok", "message": "API正常工作"}

# 尝试包含API路由
try:
    # 导入API路由
    from app.api.router import api_router
    
    # 打印API路由信息
    for route in api_router.routes:
        logger.info(f"发现路由: {route.path}, 方法: {route.methods}, 名称: {route.name}")
    
    # 包含API路由
    app.include_router(api_router, prefix=settings.API_PREFIX)
    logger.info("API路由加载成功")
except Exception as e:
    logger.error(f"API路由加载失败: {str(e)}")
    logger.error(f"异常堆栈: {traceback.format_exc()}")
    # 创建一个简单的路由，以便应用程序仍然可以启动
    @app.get(f"{settings.API_PREFIX}/error")
    async def api_error():
        return {"error": "API路由加载失败，请检查日志"}


@app.middleware("http")
async def add_process_time_header(request: Request, call_next) -> Response:
    """添加处理时间头部的中间件"""
    start_time = time.time()
    try:
        logger.info(f"处理请求: {request.method} {request.url.path}")
        response = await call_next(request)
        process_time = time.time() - start_time
        response.headers["X-Process-Time"] = str(process_time)
        logger.info(f"请求处理完成: {request.method} {request.url.path}, 状态码: {response.status_code}, 耗时: {process_time:.4f}秒")
        return response
    except Exception as e:
        logger.error(f"请求处理失败: {request.method} {request.url.path}, 错误: {str(e)}")
        import traceback
        logger.error(traceback.format_exc())
        process_time = time.time() - start_time
        return JSONResponse(
            status_code=500,
            content={"error": "内部服务器错误", "message": str(e)},
            headers={"X-Process-Time": str(process_time)}
        )


@app.exception_handler(BaseAppException)
async def app_exception_handler(request: Request, exc: BaseAppException) -> JSONResponse:
    """处理应用程序异常"""
    logger.error(f"应用程序异常: {exc.message}")
    return JSONResponse(
        status_code=exc.status_code,
        content=exc.to_dict()
    )


@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception) -> JSONResponse:
    """处理一般异常"""
    logger.error(f"未处理的异常: {str(exc)}")
    return JSONResponse(
        status_code=500,
        content={"error": {"code": "INTERNAL_ERROR", "message": "内部服务器错误", "details": {}}}
    )


@app.get("/")
async def root():
    """根路径处理程序 - 重定向到前端页面"""
    from fastapi.responses import FileResponse
    try:
        logger.info("访问根路径，返回前端页面")
        return FileResponse("static/index.html")
    except Exception as e:
        logger.error(f"根路径处理程序错误: {str(e)}")
        import traceback
        logger.error(traceback.format_exc())
        return {
            "name": "Text2SQL RAG API",
            "version": "0.1.0",
            "description": "Text-to-SQL system using RAG approach",
            "status": "error",
            "error": str(e)
        }


@app.get("/health")
async def health_check() -> Dict[str, str]:
    """健康检查端点"""
    logger.debug("健康检查")
    return {"status": "ok"}

@app.get("/{path:path}")
async def frontend_routes(path: str):
    """处理前端路由，返回 index.html"""
    # 如果路径以 api 开头，则不处理（让 API 路由处理）
    if path.startswith("api/") or path == "api":
        return {"error": "Not Found"}
    
    # 对于其他路径，返回前端页面
    from fastapi.responses import FileResponse
    logger.info(f"访问前端路径: {path}，返回前端页面")
    return FileResponse("static/index.html")


@app.on_event("startup")
async def startup_event():
    """应用程序启动事件"""
    try:
        # 初始化数据库
        from app.core.db_init import initialize_database
        await initialize_database()
        logger.info("数据库初始化完成")
        
        # 初始化向量集合
        from app.core.vector_init import initialize_vector_collections
        await initialize_vector_collections()
        logger.info("向量集合初始化完成")
        
        # 初始化 LiteLLM 配置
        import os
        import litellm
        
        # 设置 Ollama API 基础 URL
        ollama_base_url = settings.OLLAMA_BASE_URL
        litellm.ollama_api_base = ollama_base_url
        os.environ["OLLAMA_API_BASE"] = ollama_base_url
        
        # 如果使用的是 Ollama 模型，设置模型配置
        if settings.LITELLM_MODEL.startswith("ollama/"):
            model_name = settings.LITELLM_MODEL.split("/")[1]  # 获取模型名称，例如 "qwen2.5:latest"
            litellm.model_list = [
                {
                    "model_name": f"ollama/{model_name}",
                    "litellm_params": {
                        "api_base": ollama_base_url
                    }
                }
            ]
        
        logger.info(f"LiteLLM 配置初始化完成，Ollama 服务 URL: {ollama_base_url}")
        
        logger.info(f"{settings.APP_NAME} 启动成功")
    except Exception as e:
        logger.error(f"应用程序启动失败: {str(e)}")
        import traceback
        logger.error(traceback.format_exc())


@app.on_event("shutdown")
async def shutdown_event():
    """应用程序关闭事件"""
    logger.info(f"{settings.APP_NAME} 关闭")